const http = require('http');
const fs = require(`fs`);
const path = require('path');
const { promisify } = require('util');

let app = http.createServer();

app.on('request', (req, res) => {
    let filePath = path.join(__dirname, 'test.png');
    let file = fs.statSync(filePath);
    let start = 0, total = file.size, end = total;
    // 获取请求范围
    if (req.headers.range) {
        let range = req.headers.range.match(/bytes=(\d+)-(\d+)/);//bytes=0-100
        start = range[1] ? parseInt(range[1]) : 0;
        end = range[2] ? parseInt(range[2]) : total;
        // bytes 0 100/
        res.setHeader('Content-Range', `bytes ${start}-${end}/${total}`);
    }
    res.setHeader('Content-Type', 'image/png');
    console.log(start, end, total)
    // 截取范围内的文件给客户端
    fs.createReadStream(filePath, { start, end }).pipe(res);
})

app.listen(8080, () => console.log("Server start at 8080"));